import React, { Component } from 'react'
//导入css样式
import '../assets/css/Cate.css'

//导入请求的接口
import { cateRequest, goodsRequest } from '../request/cate_request'
import Header from "../components/DefaultHeader"

export default class Cate extends Component {
    state = {
        cate_list: [],
        cate_id: 1,
        cate_name: "时令水果",
        good_list: []
    }
    //点击导航切换对应的商品
    change_goods(cate_id, cate_name) {
        this.setState({ cate_id, cate_name })
        //根据id获取分类商品的商品分类
        goodsRequest(cate_id).then((res) => {
            this.setState({ good_list: res.list })
        })
    }
    UNSAFE_componentWillMount() {
        //商品分类的数据请求并赋值
        cateRequest().then((res) => {
            this.setState({ cate_list: res.list })
            //初始化页面
            let obj = res.list[0]
            this.change_goods(obj.id, obj.catename)
        })
    }
    render() {
        const { cate_list, cate_id, cate_name, good_list } = this.state
        return (
            <div id='cate'>
                <Header title='商品分类'/>
                <div className="content">
                    <ul className="left">
                        {
                            cate_list.map((item) => (
                                <li key={item.id} className={item.id === cate_id ? 'active' : ''} onClick={() => this.change_goods(item.id, item.catename)}>{item.catename}</li>
                            ))
                        }
                    </ul>
                    <ul className="right">
                        <li className="section">
                            <h3>{cate_name} <span onClick={() => this.props.history.push('/goodsList?type_id=' + cate_id + '&type_name=' + cate_name)}>查看更多&gt;&gt;</span></h3>
                            <ul>
                                {
                                    good_list.map((item) => (
                                        <li key={item.id}>
                                            <img src={this.$static_host + item.img} alt="" onClick={() => this.props.history.push('/goods_detail?id=' + item.id)} />
                                            <p>{item.goodsname}</p>
                                        </li>
                                    ))
                                }

                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        )
    }
}
